package com.hebau.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hebau.usercenter.common.BaseResponse;
import com.hebau.usercenter.common.ErrorCode;
import com.hebau.usercenter.common.ResultUtils;
import com.hebau.usercenter.exception.BusinessException;
import com.hebau.usercenter.model.domain.User;
import com.hebau.usercenter.model.request.UserLoginRequest;
import com.hebau.usercenter.model.request.UserRegisterRequest;
import com.hebau.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.hebau.usercenter.constant.UserConstant.ADMIN_ROLE;
import static com.hebau.usercenter.constant.UserConstant.USER_LOGIN_STATE;

@RequestMapping("/user")
@RestController
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.PARAM_NULL, "请求参数为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String uniqueCode = userRegisterRequest.getUniqueCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword,uniqueCode)){
            throw new BusinessException(ErrorCode.PARAM_NULL, "请求参数为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, uniqueCode);
        return ResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.PARAM_NULL, "请求参数为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAM_NULL, "请求参数为空");
        }
        User user = userService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request){
        if (request == null){
            throw new BusinessException(ErrorCode.PARAM_NULL, "请求参数为空");
        }

        int result = userService.userLogout(request);
        return ResultUtils.success(result);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> search(String userName, HttpServletRequest request){
        // 注意一定要用户鉴权
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        // 允许空查询
        /*if (StringUtils.isEmpty(userName)){
            return new ArrayList<>();
        }*/
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNoneBlank(userName)){
            queryWrapper.like("username", userName);
        }
        List<User> userList = userService.list(queryWrapper);
        // 用户脱敏
        List<User> users = userList.stream().map(user -> {
            userService.getSafetyUser(user);
            return user;
        }).collect(Collectors.toList());
        return ResultUtils.success(users);
    }


    /**
     * 删除用户
     *
     * @param id
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> delete(Integer id, HttpServletRequest request){
        // 注意一定要用户鉴权
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if (id == null || id <= 0){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "该用户 ID 不存在");
        }
        boolean result = userService.removeById(id);// 开启逻辑删除，MP会自动将逻辑删除改为更新

        return ResultUtils.success(result);
    }

    /**
     * 用户鉴权
     * @param request 请求
     * @return boolean
     */
    private boolean isAdmin(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != ADMIN_ROLE){ // 注意 user 为 null 会报 NPE,
            return false;
        }

        return true;
    }

}
